package com.ruoyi.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.cg.dto.JoinGroupParams;
import com.ruoyi.common.core.cg.pojo.*;
import com.ruoyi.common.core.cg.result.OrderDetailResult;
import com.ruoyi.common.core.cg.result.PageResult;
import com.ruoyi.common.core.cg.dto.QueryPageBean;
import com.ruoyi.common.core.cg.result.Result;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.user.mapper.GroupMapper;
import com.ruoyi.user.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class GroupServiceImpl implements GroupService {
    @Autowired
    private GroupMapper mapper;
    @Autowired
    private StoreService storeService;
    @Autowired
    private CommunityService communityService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisService redisService;
    /**
     * 分页查询Group
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        // 判断redis是否存在数据
        if (redisService.getCacheObject("group:findPage:"+queryPageBean.getCurrentPage()+queryPageBean.getPageSize()+queryPageBean.getCommunityId()) != null){
            Object cacheObject = redisService.getCacheObject("group:findPage:" + queryPageBean.getCurrentPage() + queryPageBean.getPageSize() + queryPageBean.getCommunityId());
            PageResult pageResult = (PageResult) cacheObject;
            return pageResult;
        }
        // 数据校验
        if (null == queryPageBean.getCurrentPage() || queryPageBean.getCurrentPage() <= 0){
            queryPageBean.setCurrentPage(1);
        }
        if (null == queryPageBean.getPageSize()){
            queryPageBean.setPageSize(5);
        }
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        List<Group> groupList = mapper.findPage(queryPageBean.getQueryString()
        ,queryPageBean.getCommunityId(),queryPageBean.getStatus());
        for (Group group:groupList){
            Store store = storeService.findById(group.getId());
            Integer memberCount = mapper.findCurrentMemberCountByGroupId(group.getId());
            Integer groupType = groupMember(group.getPeople());
            group.setTotalGroup(memberCount / groupType);
            group.setStore(store);
        }
        PageInfo<Group> pageInfo = new PageInfo<>(groupList);
        PageResult pageResult = new PageResult(pageInfo.getTotal(),pageInfo.getList());
        System.out.println("存入redis");
        redisService.setCacheObject("group:findPage:"+queryPageBean.getCurrentPage()+queryPageBean.getPageSize(),pageResult);
        redisService.expire("group:findPage:"+queryPageBean.getCurrentPage()+queryPageBean.getPageSize()+ queryPageBean.getCommunityId(),60,TimeUnit.SECONDS);
        return pageResult;
    }

    /**
     * 查询Group
     * @param id
     * @return
     */
    @Override
    public Result findById(Integer id) {
        // 判断redis中是否存在数据
        Result redisResult = redisService.getCacheObject("group:findById:" + id);
        if (redisResult != null){
            return redisResult;
        }
        OrderDetailResult orderDetailResult = new OrderDetailResult();
        Group group = mapper.findById(id);
        Store store = storeService.findById(group.getId());
        group.setStore(store);
        Integer groupMember = groupMember(group.getPeople());
        group.setPeople(groupMember);
        Integer memberCountByGroupId = mapper.findCurrentMemberCountByGroupId(group.getId());
        group.setTotalGroup(memberCountByGroupId / groupMember);
        orderDetailResult.setGroup(group);
        List<User> userList = mapper.findUserByGroupId(group.getId());
        orderDetailResult.setUserList(userList);
        Result result = new  Result(true,"查询成功",orderDetailResult);
        // 存入redis数据
        redisService.setCacheObject("group:findById:" + id,result);
        redisService.expire("group:findById:" + id,30, TimeUnit.SECONDS);
        return result;
    }

    /**
     * 查询加入拼团点的相关信息
     * @param id 团ID
     * @return
     */
    @Override
    public JoinGroupInfo findJoinGroupInfo(Integer id) {// 判断redis是否存在数据
        // 判断redis中是否存在数据
        JoinGroupInfo redisResult = redisService.getCacheObject("group:findJoinGroupInfo:" + id);
        if (redisResult != null){
            return redisResult;
        }
        JoinGroupInfo joinGroupInfo = new JoinGroupInfo();
        Group group = mapper.findById(id);
        Community community = communityService.findCommunityByGroup(group.getId());
        Leader leader = communityService.findLeaderById(community.getId());
        Store store = storeService.findStoreByGroupId(group.getId());
        joinGroupInfo.setCommunity(community);
        joinGroupInfo.setLeader(leader);
        joinGroupInfo.setStore(store);
        joinGroupInfo.setGroup(group);
        // 存入redis数据
        redisService.setCacheObject("group:findJoinGroupInfo:" + id,joinGroupInfo);
        redisService.expire("group:findJoinGroupInfo:" + id,30, TimeUnit.MILLISECONDS);
        return joinGroupInfo;
    }

    /**
     * 询过期的团
     * @return
     */
    @Override
    public List<Integer> findByTime() {
        return mapper.findByTime();
    }

    /**
     * 修改拼团状态
     * @param groupIdList
     */
    @Override
    public void batchUpdateState(List<Integer> groupIdList) {
        mapper.batchUpdateState(groupIdList);
    }

    @Override
    public List<Map<String,Object>> findAll() {
        return mapper.findAll();
    }

    /**
     * 进团
     * @param joinGroupParams
     * @return
     */
    @Override
    @Transactional
    public Result joinGroup(JoinGroupParams joinGroupParams) {
        Integer groupId = joinGroupParams.getGroupId();
        Integer storeId = joinGroupParams.getStoreId();
        Integer userId = joinGroupParams.getUserId();
        String name = joinGroupParams.getName();
        String phone = joinGroupParams.getPhone();
        Integer quantity = joinGroupParams.getQuantity();
        //1.首先判断用户是否已经进入该团
        if (groupId != null){
            Integer exists = mapper.judgeJoinGroupOrNot(groupId,userId);
            if (exists != null){
                return new Result(false,"您已经进入该团了");
            }
        }
        //2.判断团的人数是否已满
        //2.1.首先查询团的可成团总人数为多少
        Group group = mapper.findById(groupId);
        if (null == group){
            return new Result(false,"系统出现错误");
        }
        Integer groupMember = groupMember(group.getPeople());
        Integer maxGroupCount = group.getMaxGroup();
        Integer totalMemberCount = (groupMember * maxGroupCount);
        Integer currentMemberCount = mapper.findCurrentMemberCountByGroupId(group.getId());
        //2.2.判读当前拼团人数是否超过总人数
        if (currentMemberCount >= totalMemberCount){
            return new Result(false,"拼团已满");
        }
        //3.是否拼团超时了
        long currentTimeMillis = System.currentTimeMillis();
        Date endTime = group.getEndTime();
        if (endTime.getTime() <= currentTimeMillis){
            return new Result(false,"拼团超时了");
        }
        //4.商家是否已经停止拼团
        Integer status = group.getStatus();
        if (status != 1){
            return new Result(false,"拼团已经结束");

        }
        //5.进团
        mapper.joinGroup(groupId,userId);
        //6.生成订单
        Order order = new Order();
        order.setOnumber(UUID.randomUUID().toString().replaceAll("-",""));
        // 将 Integer 转换为 BigDecimal
        BigDecimal integerAsBigDecimal = new BigDecimal(quantity);
        BigDecimal price = group.getPrice();
        BigDecimal result = price.multiply(integerAsBigDecimal);
        order.setPrice(result);
        order.setOrderStatus(0);
        order.setItemStatus(1);
        order.setCreateTime(new Date());
        order.setItemCount(quantity);
        order.setName(group.getName());
        order.setReservedName(name);
        order.setReservedPhone(phone);
        orderService.addOrder(order);
        //7.生成用户对应的订单
        userService.addUserOrder(userId,order.getOid());
        //8.生成店铺对应的订单
        storeService.addStoreOrder(storeId,order.getOid());
        //9.生成团对应的订单
        mapper.addGroupOrder(groupId,order.getOid());
        return new Result(true,"拼团成功",order.getOid());
    }

    /**
     * 查询该团所有的成员
     * @param id
     * @return
     */
    @Override
    public List<User> findGroupAllMemberByGroupId(Integer id) {
        return mapper.findGroupAllMemberByGroupId(id);
    }

    /**
     * 查询用户所处团的所有用户
     * @param id
     * @param startIndex
     * @param endIndex
     * @return
     */
    @Override
    public List<User> findGroupMemberByGroupId(Integer id, Integer startIndex, Integer endIndex) {
        return mapper.findGroupMemberByGroupId(id,startIndex,endIndex);
    }


    private Integer groupMember(Integer type){
        if (type == 0){
            return 3;
        }else if (type == 1){
            return 5;
        }else if (type == 2){
            return 10;
        }else if (type == 3){
            return 20;
        }
        return 0;
    }


}
